package net.dethnull.joscontrol.osc;

import net.dethnull.joscontrol.gui.JOSControl;

import java.awt.*;

/**
 * Project: jOSControl
 * Package: net.dethnull.joscontrol.osc
 * Author: dethnull
 * Date: 2/1/13
 * <p/>
 * <p/>
 * Description:
 */
public class Key extends Thread {

    private int _key;
    private volatile boolean threadCreated = false;
    private volatile boolean isInterrupted = false;

    private volatile boolean isKeyDown = false;

    public Key() { this.set_key(0);}

    public Key(int key) {
        this.set_key(key);
    }

    public void setThreadCreated() {
        this.threadCreated = true;
    }

    public boolean isThreadCreated() {
        return this.threadCreated;
    }

    public void set_key(int key) {
        this._key = key;
    }

    public int get_key() {
        return this._key;
    }

    public void pressKey() { this.isKeyDown = true; }
    public void releaseKey() { this.isKeyDown = false; }

    @Override
    public boolean isInterrupted() {
        return this.isInterrupted;
    }

    @Override
    public void interrupt() {
        JOSControl.addToDebugLog(super.getName() + " Thread interrupted.");
        this.isInterrupted = true;
    }

    public void reset() {
        this.isInterrupted = false;
        this.threadCreated = false;
    }

    @Override
    public void run() {
        do {
            try {
                Robot robot = new Robot();

                if (isKeyDown) {
                    //System.out.println("pressing " + get_key());
                    robot.keyPress(get_key());
                    Thread.sleep(50);
                } else {
                    //System.out.println("Waiting for keypress");
                    robot.keyRelease(get_key());
                    Thread.sleep(100);
                }
            } catch (Exception e) {
                JOSControl.addToDebugLog(e.getMessage());
            }
        }  while(!isInterrupted());
    }

}
